﻿/// <reference path="../../Scripts/jquery-1.4.1-vsdoc.js" />
/// <reference path="../../Content/Scripts/InternalMaster.js" />

var _materials = []; //id, amount

function addMaterial() {
	popupMaterials(function (m) {
		var serail = im_findItem(m.value);
		if (serail != null) {
			var htmlSegment = '\
<tr>\
    <td>\
		' + serail.material.text + '\
    </td>\
    <td>\
		' + serail.bigCate.text + '\
    </td>\
    <td>\
		' + serail.cate.text + '\
    </td>\
    <td>\
        <input type="text" value="1" onchange="_amountChange(' + serail.material.value + ', this)" />\
    </td>\
</tr>';
			$("#tableSelMaterial tbody").append(htmlSegment);
			altTable("#tableSelMaterial");

			_materials[_materials.length] = {
				"id": serail.material.value,
				"amount": 1
			};
		}
	});
}

function submitAllData() {
	var barcode = $("#txtBarcode").val();
	var name = $("#txtProductName").val();
	var description = $("#txtProductDescription").val();
	if (barcode.length == 0) {
		alert("产品条码没有填写！");
		return;
	}
	if (name.length == 0) {
		alert("产品名称没有填写！");
		return;
	}
	if (_materials.length == 0) {
		alert("没有添加任何物料！");
		return;
	}

	var matrials = _serailzeMaterials();
	$.post(actionUrl("Assemble", "AJAX_AddProductDefinition"), {
		"barcode": barcode,
		"name": name,
		"description": description,
		"materialAmount": matrials
	}, function (res) {
		alert(res.Message);
		if (res.Success) {
			window.location = actionUrl("Assemble", "ProductDefinitionList");
		}
	});
}

function _amountChange(materialId, txt) {
	var m = $.grep(_materials, function (m) {
		return m.id == materialId;
	});
	var amount = parseInt($(txt).val());
	if (!isNaN(amount)) {
		m[0].amount = amount;
	}
	else {
		alert("格式不对，只能填写数字。");
	}
}

//id=amount,id=amount,id=amount...
function _serailzeMaterials() {
	var allMaterials = "";
	$.each(_materials, function (i, m) {
		if (typeof (m) != undefined) {
			if (allMaterials.length > 0) allMaterials += ",";
			if (m.amount > 0) {
				allMaterials += m.id + "=" + m.amount;
			}
		}
	});
	return allMaterials;
}